import time
import importlib
import datetime
from flask import Blueprint, g, request, current_app
import sys
from .tools import get_wps_url, generate_token, get_context_fileid, datetime_to_timestamp
wps_bp = Blueprint('wps_bp', __name__)
@wps_bp.before_request
def before_request():
    params = {}
    if request.args:
        params.update(request.args.to_dict(flat=True))
    if request.is_json and request.get_data() and request.json:
        if type(request.json) == type([]):
            for x in request.json:
                params.update(x)
        else:
            params.update(request.json)
    if request.form:
        params.update(request.form.to_dict(flat=True))
    # 所有的请求参数
    g.params = params
    
def get_file_info(file_id):
    sys.path.append(current_app.config['MODEL_ROOT_DIR_PATH'])
    file_model_file = importlib.import_module(
        current_app.config['MODOLE_FILE_PATH'])  # 导入models模块
    File = getattr(file_model_file, current_app.config['FILE_CLASS_NAME'])  # 反射并实例化
    user_model_file = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(user_model_file, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    """ 获取文件的信息，需要开发者根据自己的项目自己实现
    Returns:
        dict:
            {
            'id': '123456',  # 文件id,字符串长度小于40
            'name': '测试文件1.xlsx',  # 文件名(必须带文件后缀)
            'version': 1,  # 当前版本号，位数小于11
            'size': '',  # 文件大小，单位为B(文件真实大小，否则会出现异常)
            'creator': '123456', # 创建者id，字符串长度小于40
            'create_time': '1234567890', # 创建时间，时间戳，单位为秒
            'modifier': '123456', # 修改者id，字符串长度小于40
            'modify_time': '1234567890', # 修改时间，时间戳，单位为秒
            'download_url': 'http://testctms.blueballon.cn/api/v1.0/ctms/file/uploads/600a3ebc365d0c79ce300df2?userid=超级管理员',  # 文档下载地址
            }
    """
    f = File.objects(id=file_id).first()
    return {
        'id': file_id,
        'name': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['name']),
        'version': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['version']),
        'size': int(getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['size'])),
        'creator': getattr(getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['creator']), current_app.config['FILE_ATTR_NAME_MAP']['name']) if getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['creator']) else '超级管理员',
        'create_time': datetime_to_timestamp(getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['create_time'])),
        'modifier': getattr(getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['modifier']), current_app.config['FILE_ATTR_NAME_MAP']['name']) if getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['modifier']) else '超级管理员',
        'modify_time': datetime_to_timestamp(getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['modify_time'])),
        'download_url': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['download_url']),
    }





def get_user_info(userid):
    model = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(model, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    user = User.objects(id=userid).first()
    """获取用户信息,需要开发者根据自己的项目自己实现

    Args:
                    userid (str): 用户的id
    Returns:
                    dict:
                                    {
                                    'id': '123456',
                                    'name': '超级管理员',
                                    'avatar_url': ''  # 用户头像地址
                                    }
    """
    return {
        'id': userid,
        'name': getattr(user, current_app.config['USER_ATTR_NAME_MAP']['name']),
        'avatar_user': getattr(user, current_app.config['USER_ATTR_NAME_MAP']['avatar_url'])
    }


@wps_bp.route('/file/info')
def file_metadata():
    """1.获取文件元数据"""
    file_id = request.headers.get('x-weboffice-file-id')
    userid = g.params.get('_w_userid')
    file_info = get_file_info(file_id)
    base_file_set = {
        'preview_pages': 3,  # 限制预览页数
        'user_acl': {
            'rename': 1,    # 重命名权限，1为打开该权限，0为关闭该权限，默认为0
            'history': 1,  # 历史版本权限，1为打开该权限，0为关闭该权限,默认为1
            'copy': 1,  # 复制
            'export': 1,  # 导出PDF
            'print': 1  # 打印
        },
        'watermark':  {
            'type': 0,  # 水印类型， 0为无水印； 1为文字水印
            'value': "禁止传阅",  # 文字水印的文字，当type为1时此字段必选
            # 水印的透明度，非必选，有默认值
            'fillstyle': "rgba( 192, 192, 192, 0.6 )",
            'font': "bold 20px Serif",  # 水印的字体，非必选，有默认值
                    'rotate': -0.7853982,  # 水印的旋转度，非必选，有默认值
                    'horizontal': 50,  # 水印水平间距，非必选，有默认值
                    'vertical': 100  # 水印垂直间距，非必选，有默认值
        }}
    file_info.update(base_file_set)
    user_info = get_user_info(userid)
    # 用户操作权限，write：可编辑，read：预览
    do_yourself = importlib.import_module('do_yourself')
    get_user_file_permission = getattr(do_yourself, 'get_user_file_permission')  # 反射并实例化
    user_info['permission'] = get_user_file_permission(userid, file_id)
    filedata = {
        'file': file_info,
        'user': user_info
    }
    print(filedata)
    return filedata


@wps_bp.route('/user/info', methods=['post'])
def get_user_batch():
    """2.获取用户信息"""
    model = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(model, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    ids = g.params.get('ids')
    res = []
    for id in ids:
        user = {}
        if id == '超级管理员':
            user['id'] = '超级管理员'
            user['name'] = '超级管理员'
            user['avatar_url'] = ''
        else:
            user_instance = User.objects(id=id).first()
            user['id'] = str(user_instance.id)
            user['name'] = getattr(
                user_instance, current_app.config['USER_ATTR_NAME_MAP']['name'])
            user['avatar_url'] = getattr(
                user_instance, current_app.config['USER_ATTR_NAME_MAP']['avatar_url'])
        res.append(user)
    return {
        'users': res
    }


@wps_bp.route('/file/save', methods=['post'])
def post_save_file():
    """3.上传文件新版本"""
    sys.path.append(current_app.config['MODEL_ROOT_DIR_PATH'])
    file_model_file = importlib.import_module(
        current_app.config['MODOLE_FILE_PATH'])  # 导入models模块
    File = getattr(file_model_file, current_app.config['FILE_CLASS_NAME'])  # 反射并实例化
    user_model_file = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(user_model_file, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    user = User.objects(id=g.params.get('_w_userid')).first()
    fileid = get_context_fileid()
    file_instance = File.objects(id=fileid).first()
    if not file_instance:
        print("err : file not exist")
        return {
            "code": 40005,
            "message": "InvalidRequest",
            "details": "fileid:{} not exist".format(fileid),
            "hint": "fileid:{} not exist".format(fileid)
        }
    file_stream = request.files['file']
    size = len(file_stream.read())
    # 创建文件新版本
    file_obj = File()
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['size'], size)
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['name'], getattr(
        file_instance, current_app.config['FILE_ATTR_NAME_MAP']['name']))
    file_stream.seek(0)
    getattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['file_stream']).put(file_stream)
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['version'], int(
        time.time()))
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['creator'], user)
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['create_time'], datetime.datetime.now())
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['modifier'], user)
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['modify_time'], datetime.datetime.now())
    f = file_obj.save()
    path = current_app.config['FILE_DOWNLOAD_URL'] + \
        '?fileid={}'.format(str(f.id))
    print(current_app.config['FILE_ATTR_NAME_MAP']['download_url'])        
    setattr(file_obj, current_app.config['FILE_ATTR_NAME_MAP']['download_url'], path)
    for new_old_need_same_attr in current_app.config['NEW_OLD_NEED_SAME_ATTR_LIST']:
        setattr(file_obj, new_old_need_same_attr, getattr(
            file_instance, new_old_need_same_attr))
    f.save()
    f.reload()
    return {
        'file': {
            'id': str(f.id),  # 文件id，字符串长度小于40
            # 文件名
            'name': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['name']),
            # 当前版本号，位数小于11
            'version': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['version']),
            # 文件大小，单位是B
            'size': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['size']),
            # 文件下载地址
            'download_url': getattr(f, current_app.config['FILE_ATTR_NAME_MAP']['download_url'])
        }
    }


@wps_bp.route('/file/online', methods=['post'])
def post_file_online():
    """上传在线编辑用户信息"""
    sys.path.append(current_app.config['ROOT_DIR_PATH'])
    sys.path.append(current_app.config['MODEL_ROOT_DIR_PATH'])
    model = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(model, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    ids = g.params.get('ids')
    fileid = get_context_fileid()
    res = []
    for id in ids:
        user = {}
        permission = None
        if id == '超级管理员':
            user['id'] = '超级管理员'
            user['name'] = '超级管理员'
            user['avatar_url'] = ''
            permission = 'write'
        else:
            user_instance = User.objects(id=id).first()
            user['id'] = str(user_instance.id)
            user['name'] = getattr(
                user_instance, current_app.config['USER_ATTR_NAME_MAP']['name'])
            user['avatar_url'] = getattr(
                user_instance, current_app.config['USER_ATTR_NAME_MAP']['avatar_url'])
            do_yourself = importlib.import_module('do_yourself')  # 导入models模块
            get_user_file_permission = getattr(do_yourself, 'get_user_file_permission')  # 反射并实例化
            permission = get_user_file_permission(user_instance.id, fileid)
        user['permission'] = permission
        res.append(user)
    return {
        'users': res
    }


@wps_bp.route('/file/version/<int:version>')
def file_version(version):
    """获取特定版本的文件信息"""
    
    model = importlib.import_module(
        current_app.config['MODOLE_FILE_PATH'])  # 导入models模块
    File = getattr(model, current_app.config['FILE_CLASS_NAME'])  # 反射并实例化
    fileid = get_context_fileid()
    file_instance = File.objects(id=fileid).first()
    if not file_instance:
        print("err : file not exist")
        return {
            'details': "fileid:{} not exist".format(fileid),
            'hint': "fileid:{} not exist".format(fileid)
        }
    fname = getattr(
        file_instance, current_app.config['FILE_ATTR_NAME_MAP']['name'])
    file_obj = {
        'file': {
            'id': str(file_instance.id),  # 文件id,字符串长度小于40
            'name': fname,  # 文件名
            # 当前版本号，位数小于11
            'version': getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['version']),
            # 文件大小，单位为B
            'size': getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['size']),
            # 创建时间，时间戳，单位为秒
            'create_time': getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['create_time']),
            # 创建者id，字符串长度小于40
            'creator': getattr(getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['creator']), current_app.config['FILE_ATTR_NAME_MAP']['name']) if getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['creator']) else '超级管理员',
            # 修改时间，时间戳，单位为秒
            'modify_time': getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['modify_time']),
            # 修改者id，字符串长度小于40
            'modifier': getattr(getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['modifier']), current_app.config['FILE_ATTR_NAME_MAP']['name']) if getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['modifier']) else '超级管理员',
            # 文档下载地址
            'download_url': getattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['download_url'])
        }
    }
    return file_obj


@wps_bp.route('/file/rename', methods=['post'])
def put_file_name():
    """文件重命名"""
    sys.path.append(current_app.config['MODEL_ROOT_DIR_PATH'])
    file_model_file = importlib.import_module(
        current_app.config['MODOLE_FILE_PATH'])  # 导入models模块
    File = getattr(file_model_file, current_app.config['FILE_CLASS_NAME'])  # 反射并实例化
    user_model_file = importlib.import_module(
        current_app.config['MODOLE_USER_PATH'])  # 导入models模块
    User = getattr(user_model_file, current_app.config['USER_CLASS_NAME'])  # 反射并实例化
    user = User.objects(id=g.params.get('_w_userid')).first()
    model = importlib.import_module(
        current_app.config['MODOLE_FILE_PATH'])  # 导入models模块
    File = getattr(model, current_app.config['FILE_CLASS_NAME'])  # 反射并实例化
    fileid = get_context_fileid()
    file_instance = File.objects(id=fileid).first()
    print(file_instance)
    setattr(file_instance,
            current_app.config['FILE_ATTR_NAME_MAP']['name'], g.params.get('name'))
    setattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['modifier'], user)
    setattr(file_instance, current_app.config['FILE_ATTR_NAME_MAP']['modify_time'], datetime.datetime.now())
    file_instance.save()
    return {
        'code': 0,
        'msg': '文件重命名成功'
    }


def get_file_history_versions():
    """获取所有历史版本文件信息"""
    pass


@wps_bp.route('/onnotify', methods=['post'])
def post_notification():
    """获取企业信息"""
    return {'msg': 'success'}


@wps_bp.route('/get_url_and_token')
def get_url_and_token_handler():
    """获取url和token"""
    sys.path.append(current_app.config['MODEL_ROOT_DIR_PATH'])
    fileid = g.params.get('fileid')
    userid = g.params.get('userid')
    wps_url = get_wps_url(fileid, userid)
    token = generate_token()
    data = {
        "token":      token,
        "wps_url":     wps_url,
    }
    return data
